<?php

class PayTtCompletedService
{
    /**
     * @var PayTtCompletedService
     */
    private static $instance;

    /**
     * Get the instance of PayTtCompletedService
     * @return PayTtCompletedService
     */
    public static function get()
    {
        if (!self::$instance) {
            self::$instance = new PayTtCompletedService();
        }
        return self::$instance;
    }

    /**
     * Construction.
     */
    public function __construct()
    {
    }

    /**
     * @param $userId
     * @param $orderId
     * @return array|false|string
     * @throws SzException
     */
    public function ttPayCompleted($userId, $orderId, $isCallback = 0)
    {
        $reqTime = GameService::get()->getSysTime();

        //查询数据库，订单是否存在
        /**
         * @var ModulePaymentOrderVoList $paymentList
         * @var ModulePaymentOrderVo $payment
         */
        $paymentList = SzPersister::get()->getVoList($userId, ModulePaymentConst::ORM_NAME_PAYMENT_ORDER);
        $payment = $paymentList->getElement($orderId, false);
        $getParams = json_decode($payment->getExtra(), true);//ext扩展信息，json格式
        $price = $getParams['price'];
        $type = $getParams['type'];
        $goodId = $getParams['goodId'];
        $count = $getParams['count'];

        //设置订单状态
        if (!$payment) {
            SzLogger::get()->error('OrderSqlData-Non-existent!');
            echo 'result=FAIL&resultMsg=7+OrderSqlDataNonexistent';
            exit();
        }

        if ($payment->getStatus() == 2) {
            SzLogger::get()->error('OrderReward-Has-Get!');
            echo 'result=FAIL&resultMsg=99+OrderRewardHasGet';
            exit();
        }
        $payment->setStatus(1);
        $payment->setCompleteTime($reqTime);
        if ($isCallback > 0) {
            $payment->setPlatformToken($payment->getPaymentDefId());
        }
        $payment->persist();
        $paymentList->updateElement($orderId, $payment);
        SzPersister::get()->setVoList($paymentList);

        error_log('-------道具发放开始===>' . "\r\n", 3, $_ENV['LOG_ROOT'] . '/payment-' . date('Y-m-d') . '.log');

        $giftConf = [];
        //充值购买物品配置表获取==>1:ft_diamond_gift_pack---2:ft_game_pay---3:ft_diamond_value
        switch ($type) {
            case 1: // 等级段礼包礼包和玫瑰礼包
                $giftConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_DIAMOND_GIFT_PACK, $goodId, true);
                break;
            case 2: // 钻石，钻石页签的内容
                $giftConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_PAY, $goodId, true);
                break;
            case 3: // 钻石价值表，金币页签和特惠页签的内容
                $giftConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_DIAMOND_VALUE, $goodId, true);
                break;
            default:
                break;
        }

        // 支付回调bug修复
        $_SERVER['is_payment_callback'] = true;

        $result = $this->branchShop($userId, $giftConf, $type, $goodId, $count, $orderId, $reqTime);

        unset($_SERVER['is_payment_callback']);

        if ($result['code'] != 0) {
            error_log('-------道具发放失败===>' . "\r\n", 3, $_ENV['LOG_ROOT'] . '/payment-' . date('Y-m-d') . '.log');
        } else {
            error_log('-------道具发放OK===>' . "\r\n", 3, $_ENV['LOG_ROOT'] . '/payment-' . date('Y-m-d') . '.log');
        }

        try {
            //充值返利 ，支付成功主动回调
            $platform = PlatformBase::PLATFORM_TT;
            $platform = GameConst::PLATFORM_TIME_ARRAY[$platform];
            $activity = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_EVENT, null, true);
            $activityIds = [];
            foreach ($activity as $aid => $conf) {
                if ($conf['type'] == 12) {
                    $startTime = strtotime($conf[$platform . 'TriggerTime']);
                    $endTime = strtotime($conf[$platform . 'EndTime']);
                    if ($reqTime > $startTime && $reqTime < $endTime) {
                        $activityIds[] = $conf['indexId'];
                    }
                }
            }

            if ($activityIds) {
                foreach ($activityIds as $key => $activityId) {
                    ActivityService::get()->activityPayNew($userId, $activityId, $price, $platform, $reqTime);
                }
            }
        } catch (\Exception $exception) {
            error_log('-------CallBackEnd===>Exception' . $exception->getMessage() . ", File: " . $exception->getFile() . ', Line: ' . $exception->getLine(), 3, $_ENV['LOG_ROOT'] . '/payment-' . date('Y-m-d') . '.log');
        }

        $end_date = date("Y-m-d H:i:s", GameService::get()->getSysTime());
        error_log('-------CallBackEnd===>end_date ' . $end_date . "\r\n\r\n\r\n", 3, $_ENV['LOG_ROOT'] . '/payment-' . date('Y-m-d') . '.log');

        $result = json_encode(array('message' => 'ok'));
        return $result;
    }


    /**
     * 购买逻辑分支
     * @param $userId
     * @param $giftConf
     * @param $type
     * @param $indexId
     * @param $count
     * @param $orderId
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function branchShop($userId, $giftConf, $type, $indexId, $count, $orderId, $reqTime)
    {
        $res = array(
            'code' => -1,
            'items' => array(),
            'itemStr' => ''
        );

        //充值购买物品配置表获取==>1:ft_diamond_gift_pack---2:ft_game_pay---3:ft_diamond_value
        switch ($type) {
            case 1: // 等级段礼包礼包和玫瑰礼包
                $changeRes = $this->buyDiamondGiftPack($userId, $giftConf, $count, $reqTime);
                break;
            case 2: // 钻石，钻石页签的内容
                $batch = 9;
                $changeRes = $this->buyGamePay($userId, $giftConf, $reqTime, $batch);
                break;
            case 3: // 钻石价值表，金币页签和特惠页签的内容
                $changeRes = $this->buyDiamondValue($userId, $indexId);
                break;
            default:
                $changeRes = [];
                break;
        }

        if ($changeRes['code'] == 0) {
            $res['code'] = $changeRes['code'];
            $res['items'] = $changeRes['items'];
            $res['itemStr'] = $changeRes['itemStr'];
        }

        return $res;
    }

    /**
     * 等级段礼包礼包和玫瑰礼包
     * @param $userId
     * @param $giftConf
     * @param $count
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function buyDiamondGiftPack($userId, $giftConf, $count, $reqTime)
    {
        $getReward = array();
        $giftPackageId = $giftConf['giftPackageId'];

        $res = array(
            'code' => -1,
            'items' => array(),
            'itemStr' => ''
        );

        /**
         * @var $userGiftPackList GiftPackVoList
         * @var $userGiftPack GiftPackVo
         */
        $userGiftPackList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_GIFT_PACK);
        $userGiftPack = $userGiftPackList->getElement($giftPackageId, false);

        //获取巡回礼包配置
        $tourGiftConfs = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_TOUR, null, true, false);

        //获取使用配置
        $key = 0;
        $useConf = array();
        $needGiftArr = array();
        foreach ($tourGiftConfs as $id => $data) {
            if (in_array($giftPackageId, $data['giftId'])) {
                $key = $id;
                $useConf = $data;
                $needGiftArr = $data['giftId'];
                break;
            }
        }

        $isCreat = false;
        if (in_array($giftPackageId, $needGiftArr)) {
            if ($userGiftPack) {
                $userGiftPack->setStatus(1);
            } else {
                $isCreat = true;
                $userGiftPack = new GiftPackVo(
                    $userId,
                    $giftPackageId,
                    1,
                    $reqTime,
                    0,
                    true
                );
            }
        }

        $outputTid = '';
        $diamond = 0;
        /**
         * @var ModuleItemVoList $itemList
         */
        $itemList = null;
        $index = 0;
        foreach ($giftConf['rewardProps'] as $entityId => $count) {
            $index++;
            if ($giftConf['type'] == 3) {//组合礼包
                $itemList = is_null($itemList) ? SzPersister::get()->getVoList($userId, ModuleItemConst::ORM_NAME_ITEM) : $itemList;
                list($action, $module, $itemDefId) = EntityService::get()->parseEntityId($entityId);
                if ($action == GameConst::ENTITY_ACTION_GET && $module == GameConst::ENTITY_TYPE_ITEM) {
                    $itemSetting = SzConfig::get()->loadAppConfig(ModuleItemConst::CONFIG_ITEM_DEFS, $itemDefId, true);
                    if ($itemSetting['category'] == GameConst::ITEM_CATEGORY_CULTIVATE_CARD) {
                        $item = $itemList->getElementsByItemDefId($itemDefId);
                        if ($item) {//组合礼包中如果有培育卡且已经获得过则换成对应的钻石
                            $diamond += $giftConf['conversionRatio'][$index - 1];
                            continue;
                        }
                    }
                }
            }
            GameService::get()->handleEntity($userId, $entityId, $count, true);
            $outputTid .= $entityId . ':' . $count . '|';

            //记录所获得物品
            if (!isset($getReward[$entityId])) {
                $getReward[$entityId] = $count;
            } else {
                $getReward[$entityId] = $getReward[$entityId] + $count;
            }
        }

        foreach ($giftConf['diamond'] as $entityId => $count) {
            if ($entityId == GameConst::ENTITY_ACTION_GET_MONEY && $count > 0) {
                $diamond += $count;
            }
        }

        if ($diamond > 0) {
            GameService::get()->handleEntity($userId, GameConst::ENTITY_ACTION_GET_MONEY, $diamond, true);
            $outputTid .= GameConst::ENTITY_ACTION_GET_MONEY . ':' . $diamond . '|';

            //记录所获得物品
            if (!isset($getReward[GameConst::ENTITY_ACTION_GET_MONEY])) {
                $getReward[GameConst::ENTITY_ACTION_GET_MONEY] = $count;
            } else {
                $getReward[GameConst::ENTITY_ACTION_GET_MONEY] = $getReward[GameConst::ENTITY_ACTION_GET_MONEY] + $count;
            }
        }

        //装饰物礼包的处理
        if ($giftConf['type'] == 8) {
            $trimmingRewardInfo = explode(':', $giftConf['specialId']);
            if ($trimmingRewardInfo[0] == GameConst::SPECIAL_ITEM_TYPE_2) {
                $trimmingReward = explode(',', $trimmingRewardInfo[1]);
                $profileInfoList = SzPersister::get()->getVoList($userId, ModuleProfileConst::ORM_NAME_PROFILE_INFO);
                $trimmingInfo = UserService::get()->getInfo($userId, GameConst::USER_INFO_TYPE_TRIMMING_INFO, $profileInfoList);
                if (is_null($trimmingInfo)) {
                    $trimmingInfo = [];
                }
                foreach ($trimmingReward as $key => $trimmingId) {
                    if (!in_array($trimmingId, $trimmingInfo)) {
                        $trimmingInfo[] = (int)$trimmingId;
                    }
                }
                UserService::get()->updateProfileInfo($userId, GameConst::USER_INFO_TYPE_TRIMMING_INFO, $trimmingInfo, $profileInfoList);
            }

        }

        if ($isCreat) {
            $userGiftPack->persist();
            $userGiftPackList->addElement($userGiftPack);
            $userGiftPackList->setElement($giftPackageId, $userGiftPack);
        } else {
            $userGiftPack->setStatus(1);
            $userGiftPack->persist();
            $userGiftPackList->updateElement($giftPackageId, $userGiftPack);
        }

        SzPersister::get()->setVoList($userGiftPackList);

        if (!empty($key) && !empty($useConf) && !empty($needGiftArr)) {
            /**
             * @var TourGiftVoList $tourGiftList
             * @var TourGiftVo $tourGiftInfo
             */
            //获取玩家巡回礼包数据
            $tourGiftList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_TOUR_GIFT);
            $tourGiftInfo = $tourGiftList->getElement($useConf['id'], false);

            if (!$tourGiftInfo) {//新建巡回礼包数据
                $tourGiftInfo = new TourGiftVo(
                    $userId,
                    $useConf['id'],
                    json_encode((string)$giftPackageId),
                    json_encode('0,0'),
                    $reqTime,
                    0,
                    true
                );
            } else {
                $num = 0;
                $buyInfo = json_decode($tourGiftInfo->getBuySituation());
                if (!empty($buyInfo) || $buyInfo != '') {
                    $bugArr = explode(',', $buyInfo);
                    if (!in_array($giftPackageId, $bugArr)) {
                        $num = count($bugArr) + 1;
                    } else {
                        $num = count($bugArr);
                    }
                }
                if ($num == 0 || $num == 1) {
                    $tourGiftInfo->setBuySituation((string)$giftPackageId);
                    $tourGiftInfo->setRewardSituation('0,0');
                } else {
                    $tourGiftInfo->setBuySituation($buyInfo . ',' . $giftPackageId);
                    $getSituation = json_decode($tourGiftInfo->getRewardSituation());
                    $getSituationArr = explode(',', $getSituation);
                    if ($num == 2) {
                        if ($getSituationArr[0] != 2) {
                            $getSituationArr[0] = 1;
                        }
                    }
                    if ($num == 3) {
                        if ($getSituationArr[1] != 2) {
                            $getSituationArr[1] = 1;
                        }
                    }

                    $tourGiftInfo->setRewardSituation(implode(',', $getSituationArr));
                }
            }

            $tourGiftInfo->persist();
            if ($tourGiftInfo->isInsert() && !SzUtility::checkArrayKey($useConf['id'], $tourGiftList->getList())) {
                $tourGiftList->addElement($tourGiftInfo);
                $tourGiftList->setElement($useConf['id'], $tourGiftInfo);
            } else {
                $tourGiftList->updateElement($useConf['id'], $tourGiftInfo);
            }

            SzPersister::get()->setVoList($tourGiftList);
        }

        // 数据采集:行为
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
            'clientData' => array(
                'tid' => 'Module:cash|action:exchange|',
                'item' => $giftPackageId,
                'value' => 1
            )
        ));

        // 数据采集
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USE_GOLD, array(
            'clientData' => array(
                'item' => 'cash&exchange&' . $giftPackageId,
                'value' => $giftConf['price']
            )
        ));

        // 数据采集
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_RESOURCE_OUTPUT, array(
            'clientData' => array(
                'tid' => $outputTid,
                'item' => 'cash&exchange&' . $giftPackageId,
            )
        ));

        if (!empty($getReward)) {
            $res['code'] = 0;
            $res['items'] = $getReward;
        }

        return $res;
    }

    /**
     * 钻石，钻石页签的内容
     * @param $userId
     * @param $giftConf
     * @param $reqTime
     * @param $activityId
     * @return array
     * @throws SzException
     */
    public function buyGamePay($userId, $giftConf, $reqTime, $activityId)
    {
        $res = array(
            'code' => -1,
            'items' => array(),
            'itemStr' => ''
        );

        $totalMoney = 0;
        $money = $giftConf['price'] * 10;
        $activity = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_EVENT, $activityId, true);

        $gamePaySettings = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_PAY, null, true);
        $reward = array();
        foreach ($gamePaySettings as $gamePaySetting) {
            if ($gamePaySetting['count'] == $money) {
                $reward = $gamePaySetting;
                break;
            }
        }

        /*  if (!$reward) {
              return $res;
          }*/

        /**
         * @var $activityFirstPayList ActivityFirstPayVoList
         * @var $activityFirstPay ActivityFirstPayVo
         */
        $activityFirstPayList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_ACTIVITY_FIRST_PAY);
        $activityFirstPay = $activityFirstPayList->getElement($money, false);
        if ($activityFirstPay) {
            $totalMoney = $money;
//            $activityFirstPay->setBatch($activity['parms']);
            $activityFirstPay->setUpdateTime($reqTime);
        } else {
            $totalMoney = $money * 2;
            $activityFirstPay = new ActivityFirstPayVo($userId, $money, $activityId, $reqTime, true);
        }
        $activityFirstPay->persist();

        if ($activityFirstPay->isInsert() && !SzUtility::checkArrayKey($money, $activityFirstPayList->getList())) {
            $activityFirstPayList->addElement($activityFirstPay);
            $activityFirstPayList->setElement($money, $activityFirstPay);
        } else {
            $activityFirstPayList->updateElement($money, $activityFirstPay);
        }

        GameService::get()->handleEntity($userId, GameConst::ENTITY_ACTION_GET_MONEY, $totalMoney, true);

        SzPersister::get()->setVoList($activityFirstPayList);

        $res['code'] = 0;
        $res['items'][GameConst::ENTITY_ACTION_GET_MONEY] = $totalMoney;
        return $res;

    }

    /**
     * 钻石价值表，金币页签和特惠页签的内容
     * @param $userId
     * @param $indexId
     * @return array
     * @throws SzException
     */
    public function buyDiamondValue($userId, $indexId)
    {
        $getReward = array();
        $res = array(
            'code' => -1,
            'items' => array(),
            'itemStr' => ''
        );

        $diamondSetting = SzConfig::get()->loadAppConfig(GameConst::CONFIG_DIAMOND_VALUE, $indexId, true);

        // 每日礼包 && 每周礼包
        if (in_array($diamondSetting['type'], [6, 9])) {
            /**
             * @var  $dailyGiftPackList DailyGiftPackVoList
             * @var $dailyGiftPack DailyGiftPackVo
             */
            $reqTime = GameService::get()->getReqTime();
            $dailyGiftPackList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_DAILY_GIFT_PACK);
            $dailyGiftPack = $dailyGiftPackList->getElement($indexId, false);
            if (!$dailyGiftPack) {
                $dailyGiftPack = new DailyGiftPackVo($userId, $indexId, 0, true);
            }

            $dailyGiftPack->setUpdateTime($reqTime);
            $dailyGiftPack->persist();
            if ($dailyGiftPack->isInsert() && !SzUtility::checkArrayKey($indexId, $dailyGiftPackList->getList())) {
                $dailyGiftPackList->addElement($dailyGiftPack);
                $dailyGiftPackList->setElement($indexId, $dailyGiftPack);
            } else {
                $dailyGiftPackList->updateElement($indexId, $dailyGiftPack);
            }

            SzPersister::get()->setVoList($dailyGiftPackList);
        }

        // 周年庆
        if ($diamondSetting['type'] == 13) {
            //验证活动是否开启
            $anniversaryAid = ActivityAnniversaryService::get()->getAnniversaryIndexId($userId);
            if ($anniversaryAid) {
                /**
                 * @var AnniversaryStepVoList $anniversaryStepList
                 * @var AnniversaryStepVo $anniversaryStep
                 */
                //获取玩家当前购买阶梯礼包的数据
                $anniversaryStepList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_ACTIVITY_ANNIVERSARY_STEP);
                $anniversaryStep = $anniversaryStepList->getElement($anniversaryAid, false);
                if ($anniversaryStep) {
                    $step = $anniversaryStep->getBuyStep();
                    if ($step + 10000 == $diamondSetting['order']) {
                        $remarks = '';
                        $serverTime = GameService::get()->getReqTime();
                        $oldGifts = json_decode($anniversaryStep->getRemarks());
                        if (empty($oldGifts) || $oldGifts == '' || $oldGifts == null || !$oldGifts) {
                            $remarks = (string)$indexId;
                        } else {
                            $remarks = $oldGifts . ',' . $indexId;
                        }

                        //修改数据
                        $anniversaryStep->setBuyStep($step + 1);
                        $anniversaryStep->setUpdateTime($serverTime);
                        $anniversaryStep->setRemarks($remarks);
                        $anniversaryStep->persist();
                        $anniversaryStepList->updateElement($anniversaryAid, $anniversaryStep);
                        SzPersister::get()->setVoList($anniversaryStepList);
                    }
                }
            }
        }

        // 基金成长
        if ($diamondSetting['type'] == 17) {
            /**
             * @var FundInfoVoList $fundInfoList
             * @var FundInfoVo $fundInfo
             */
            $fundInfoList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_FUND_INFO);
            $fundInfo = $fundInfoList->getElement($diamondSetting['indexId'], false);
            if ($fundInfo) {
                //修改数据
                $fundInfo->setStatus(1);
                $fundInfo->persist();
                $fundInfoList->updateElement($diamondSetting['indexId'], $fundInfo);
                SzPersister::get()->setVoList($fundInfoList);
            }
        }

        //合约系统
        if (in_array($diamondSetting['type'], [15, 16])) {
            //平台活动时间区分
            $platform = UserService::get()->getInfo($userId, GameConst::USER_INFO_TYPE_USER_PLATFORM);
            $platformPre = GameConst::PLATFORM_TIME_ARRAY[$platform];
            //获取合约系统的相关配置
            $contractConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_EVENT, null, true);
            //当前时间获取
            $nowTime = GameService::get()->getReqTime();
            $useConf = array();
            $isNomal = false;
            $isPoint = false;
            $changeTime = GameService::get()->getReqTime();

            foreach ($contractConf as $aid => $conf) {
                if ($conf['functionId'] == GameConst::FUNC_CONTRACT_FUNC) {
                    //验证合约期数是否正确
                    if ($platform != 'dev') {
                        $contractStart = strtotime($conf[$platformPre . 'TriggerTime']);
                        $contractEnd = strtotime($conf[$platformPre . 'EndTime']);
                    } else {
                        $contractStart = $conf['startTime'];
                        $contractEnd = $conf['endTime'];
//test0813
                        $contractStart = strtotime($conf['weixinTriggerTime']);
                        $contractEnd = strtotime($conf['weixinEndTime']);
                    }

                    if ($nowTime >= $contractStart && $nowTime <= $contractEnd) {
                        $useConf = $conf;
                        if ($diamondSetting['type'] == 15) {
                            $isNomal = true;
                        }
                        if ($diamondSetting['type'] == 16) {
                            $isPoint = true;
                        }
                        break;
                    }
                }
            }

            if ($useConf) {
                //获取玩家等级
                $userLevel = UserService::get()->getUserLevel($userId);
                //获取玩家和合约数据
                /**
                 * @var $contractRewardList ContractRewardVoList
                 * @var $contractReward ContractRewardVo
                 */
                $contractRewardList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_CONTRACT_REWARD);
                $contractReward = $contractRewardList->getElement($useConf['indexId'], false);
                if ($isNomal) {
                    if ($contractReward) {
                        ContractService::get()->setSeniorSituation($userId, $useConf['indexId'], $nowTime);
                    }

                    StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
                        'clientData' => array(
                            'tid' => 'Module:cash|action:contract|',
                            'item' => 'userLevel&' . $userLevel,
                            'value' => 1
                        )
                    ));
                }

                if ($isPoint) {
                    $needPoint = SzConfig::get()->loadAppConfig(ModuleProfileConst::CONFIG_PROFILE, 'contractLevelup', true);
                    //获取玩家合约数据
                    /**
                     * @var $contractDataList ContractDataVoList
                     * @var $contractData ContractDataVo
                     */
                    $contractDataList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_CONTRACT_DATA);
                    $contractData = $contractDataList->getElement($useConf['indexId'], false);
                    //积分配置处理
                    $point = 0;
                    $pointReward = explode(';', $diamondSetting['specialId']);
                    foreach ($pointReward as $key => $msg) {
                        $specialItem = explode(':', $msg);
                        if ($specialItem[0] == GameConst::SPECIAL_ITEM_TYPE_1) {
                            $point += $specialItem[1];
                        }
                    }

                    if ($point) {
                        //增加合约积分
                        $hasPoint = $contractData->getNowPoint();
                        $totalPoint = $contractData->getPoint();
                        $nowLevel = $newLevel = $contractData->getLevel();
                        if ($hasPoint + $point >= $needPoint['value']) {
                            $contractData->setNowPoint($hasPoint + $point - $needPoint['value']);
                            $contractData->setLevel($nowLevel + 1);
                            $newLevel = $nowLevel + 1;
                        } else {
                            $contractData->setNowPoint($hasPoint + $point);
                        }
                        $contractData->setPoint($totalPoint + $point);
                        $contractData->setUpdateTime($changeTime);
                        $contractData->persist();
                        $contractDataList->updateElement($useConf['indexId'], $contractData);
                        SzPersister::get()->setVoList($contractDataList);

                        //领奖状态修改
                        if ($newLevel == $nowLevel + 1) {
                            $isSenior = $contractReward->getSenior();
                            if ($isSenior) {
                                //高级奖励状态解锁
                                $seniorSituation = explode(',', json_decode($contractReward->getSeniorSituation()));
                                $seniorSituation[$newLevel - 1] = 1;
                                $contractReward->setSeniorSituation(implode(',', $seniorSituation));
                            }

                            //普通奖励状态解锁
                            $generalSituation = explode(',', json_decode($contractReward->getGeneralSituation()));
                            $generalSituation[$newLevel - 1] = 1;
                            $contractReward->setGeneralSituation(implode(',', $generalSituation));
                            $contractReward->setUpdateTime($changeTime);

                            $contractReward->persist();
                            $contractRewardList->updateElement($useConf['indexId'], $contractReward);
                            SzPersister::get()->setVoList($contractRewardList);
                        }

                        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
                            'clientData' => array(
                                'tid' => 'Module:cash|action:point|',
                                'item' => 'userLevel&' . $userLevel,
                                'value' => 1
                            )
                        ));

                        $res['itemStr'] = $diamondSetting['specialId'];
                    }
                }
            }
        }

        if ($indexId == 2002) {
            //获取玩家数据
            /**
             * @var ModuleProfileVo $profile
             * @var ModuleProfileInfoVoList $profileInfoList
             */
            $profileInfoList = SzPersister::get()->getVoList($userId, ModuleProfileConst::ORM_NAME_PROFILE_INFO);

            $profileFlag = $profileInfoList->getElement(GameConst::USER_INFO_TYPE_SKIP_VIDEO_CARD_FIRST, false);
            if (!$profileFlag) {
                //获得标记
                $profileFlag = new ModuleProfileInfoVo(
                    $userId,
                    GameConst::USER_INFO_TYPE_SKIP_VIDEO_CARD_FIRST,
                    1,
                    time(),
                    true
                );
                $profileFlag->persist();
                $profileInfoList->addElement($profileFlag);
                $profileInfoList->setElement(GameConst::USER_INFO_TYPE_SKIP_VIDEO_CARD_FIRST, $profileFlag);

                SzPersister::get()->setVoList($profileInfoList);
            }
        }

        $outputTid = '';
        if (!empty($diamondSetting['item'])) {
            foreach ($diamondSetting['item'] as $entityId => $count) {
                GameService::get()->handleEntity($userId, $entityId, $count, true);
                //记录所获得物品
                if (!isset($getReward[$entityId])) {
                    $getReward[$entityId] = $count;
                } else {
                    $getReward[$entityId] = $getReward[$entityId] + $count;
                }
                $outputTid .= $entityId . ':' . $count . '|';
            }
        }

        // 数据采集:行为
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
            'clientData' => array(
                'tid' => 'Module:cash|action:exchange|',
                'item' => $indexId,
                'value' => 1
            )
        ));

        // 数据采集
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USE_GOLD, array(
            'clientData' => array(
                'item' => 'cash&exchange&' . $indexId,
                'value' => $diamondSetting['price']
            )
        ));

        // 数据采集
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_RESOURCE_OUTPUT, array(
            'clientData' => array(
                'tid' => $outputTid,
                'item' => 'cash&exchange&' . $indexId,
            )
        ));

        $res['code'] = 0;
        $res['items'] = $getReward;
        return $res;
    }
}
